﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Windows.Forms;

namespace PIBV
{
    public class DbManager : PID_BaseClass
    {

        public DbManager(string connStr)
        {
            ConnectionString = connStr;
        }

        public void Connect()
        {
            try
            {
                if (Connection == null)
                {
                    Connection = new OleDbConnection(ConnectionString);
                }

                if (Connection.State == ConnectionState.Closed || Connection.State == ConnectionState.Broken)
                {
                    Connection.Open();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error [Connect]", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public void Disconnect()
        {
            if (Connection != null)
            {
                try
                {
                    Connection.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error [Disconnect]", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        #region Claas Factory Functions

        public T CreateObject<T>() where T : PID_BaseClass,new()
        {
            if (String.IsNullOrEmpty(ConnectionString)) 
                throw new Exception("ConnectionString is null or empty!");
            
            T obj = new T();
            obj.SetConnection(this.Connection);
            return obj;
        }

        private PID_DrawingList _instanceDrawingList;
        public PID_DrawingList DrawingListInstance
        {
            get
            {
                if (_instanceDrawingList == null)
                {
                    _instanceDrawingList = CreateObject<PID_DrawingList>();
                }

                return _instanceDrawingList;
            }
        }

        #endregion

    }
}
